const router = require('koa-router')();
const db = require('../dbs/user');
const log = require('../libs/log4js')('USERRouter');
const request = require('axios');
const md5 = require('md5-node');

function getOpenId(code) {
  return new Promise((s) => {
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=wxe264cb1921b5b756&secret=89d137f081d704af06bb156f31b090ed&js_code=${code}&grant_type=authorization_code`;
    console.log(url);
    request.get(url).then(function (response) {
      log.debug('登录结果');
      const body = response.data;
      if (body.openid) {
        s(JSON.stringify({
          code: 200,
          data: body.openid,
          msg: 'suc',
        }));
      } else {
        console.log('aaa');
        s(JSON.stringify({
          code: 100,
          msg: body.errmsg,
        }));
      }
    }).catch((e) => {
      s(JSON.stringify({
        code: 100,
        msg: '登录错误',
      }));
      log.debug('登录错误');
      log.debug(e);
    });
  });
}

router.post('/sigin', async (ctx) => {
  const req = ctx.request.body;
  log.debug('开始注册', req.userName);
  let url = `https://api.weixin.qq.com/sns/jscode2session?appid=wxe264cb1921b5b756&secret=89d137f081d704af06bb156f31b090ed&js_code=${req.code}&grant_type=authorization_code`;
  let openIdMsg = await request.get(url);
  openIdMsg = openIdMsg.data;
  if (!openIdMsg || !openIdMsg.openid) {
    ctx.body = JSON.stringify({
      code: 100,
      msg: openIdMsg.errmsg,
    });
    log.debug(`获取openID失败 => ${openIdMsg.errmsg}`);
    return;
  }
  const user = await db.getUserByOpenid(openIdMsg.openid);
  let flag;
  if (!user || user.length === 0) {
    log.debug('注册新用户');
    flag = await db.sigin({
      openid: openIdMsg.openid,
      userName: req.userName
    });
  } else {
    log.debug('老用户登录');
    flag = await db.wxlogin(user[0]);
  }
  if (!flag) {
    ctx.body = JSON.stringify({
      code: 100,
      msg: '注册失败',
    });
  } else {
    ctx.body = JSON.stringify({
      code: 200,
      data: flag.token,
      msg: 'suc',
    });
  }
});

router.post('/login', async (ctx) => {
  const req = ctx.request.body;
  log.debug('开始登录', req.userName);
  let flag = await db.wxlogin(undefined, req.token);
  if (!flag) {
    ctx.body = JSON.stringify({
      code: 100,
      msg: '注册失败',
    });
  } else {
    ctx.body = JSON.stringify({
      code: 200,
      data: flag,
      msg: 'suc',
    });
  }
});

router.post('/admin/addUser', async (ctx) => {
  const req = ctx.request.body;
  log.debug('admin 开始注册', req.userName);
  let findUser = await db.getUserByUserName();
  if (findUser && findUser[0]) {
    ctx.body = JSON.stringify({
      code: 100,
      msg: '该用户已经注册',
    });
  } else {
    const user = await db.sigin({
      userName: req.userName,
      pwd: md5(req.pwd)
    });
    ctx.body = JSON.stringify({
      code: 200,
      data: 'suc',
      msg: '注册成功',
    });
  }
});

router.post('/admin/login', async (ctx) => {
  const req = ctx.request.body;
  log.debug('admin 开始登录', req.userName);
  let flag = await db.adminLogin(req.userName, req.pwd);
  if (!flag) {
    ctx.body = JSON.stringify({
      code: 100,
      msg: '账号或密码不正确',
    });
  } else {
    ctx.body = JSON.stringify({
      code: 200,
      data: flag.token,
      msg: 'suc',
    });
  }
});
module.exports = router;
